﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="HpcSchedulerServiceContext.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace HpcSchedulerManagement
{
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;

    using RestClient;

    public class HpcSchedulerServiceContext : RestServiceContext, IHpcSchedulerServiceContext
    {
        private const string ServiceApiVersionHeader = "x-ms-version";

        private readonly string apiVersion;

        public HpcSchedulerServiceContext(IServiceCredentials serviceCredentials, Uri serviceUri, string apiVersion) 
            : base(serviceUri, serviceCredentials)
        {
            if (string.IsNullOrEmpty(apiVersion))
            {
                throw new ArgumentException("Api version must not be null or empty.", "apiVersion");
            }

            this.apiVersion = apiVersion;
        }

        protected override WebRequest CreateWebRequest(RequestContext requestContext)
        {
            var request = base.CreateWebRequest(requestContext);

            var httpWebRequest = request as HttpWebRequest;
            if (httpWebRequest != null)
            {
                var sslCertThumbprint = (this.ServiceCredentials as HpcSchedulerServiceCredentials).Certificate.Thumbprint;
                httpWebRequest.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
                {
                    if (errors == SslPolicyErrors.RemoteCertificateNameMismatch)
                    {
                        return (certificate as X509Certificate2).Thumbprint.Equals(sslCertThumbprint);
                    }

                    return true;
                };
            }

            return request;
        }

        protected override void AddHeaders(WebRequest request)
        {
            request.Headers.Add(ServiceApiVersionHeader, this.apiVersion);
        }
    }
}